import 'package:flutter/material.dart';

/// 生命周期
class LifeCycleApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _LifeCycleAppState();
}

class _LifeCycleAppState extends State<LifeCycleApp> // 组件绑定通知
    with
        WidgetsBindingObserver {
  AppLifecycleState _lastLifecycleState;

  /// 初始化状态
  @override
  void initState() {
    super.initState();
    // 添加观察
    WidgetsBinding.instance.addObserver(this);
  }

  /// 销毁
  @override
  void dispose() {
    // 移除观察
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  /// 状态改变赋值
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      _lastLifecycleState = state;
      print(state);
    });
  }

  @override
  Widget build(BuildContext context) {
    if (null == _lastLifecycleState)
      return Center(
          child: Text(
        'This widget has not observed any lifecycle changes.',
        textDirection: TextDirection.ltr,
      ));
    return Center(
        child: Text(
      'The most recent lifecycle state this widget observed was: $_lastLifecycleState.',
      textDirection: TextDirection.ltr,
    ));
  }
}
